//
//  LiveOverlayViewController.swift
//  Link
//
//  Created by melvyn on 2018/8/9.
//  Copyright © 2018年 NEET. All rights reserved.
//

import UIKit
import Starscream

class LiveOverlayViewController: UIViewController {
    
    @IBOutlet weak var emitterView: WaveEmitterView!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var inputContainer: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var giftArea: GiftDisplayArea!
    
    var comments: [Comment] = []
    var room: Live!
    
    var socket: WebSocket!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.estimatedRowHeight = 30
        tableView.rowHeight = UITableViewAutomaticDimension

//        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self](_) in
//            guard let strongSelf = self, strongSelf.comments.count > 0 else {
//                return
//            }
//            if strongSelf.tableView.contentSize.height > strongSelf.tableView.bounds.height {
//                strongSelf.tableView.contentInset.top = 0
//            }
//            let indexPath = IndexPath(row: strongSelf.comments.count - 1, section: 0)
//            strongSelf.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
//        }
        
        IHKeyboardAvoiding.setAvoiding(inputContainer)

        socket.onData = { [weak self]data in
            let bytes: [UInt8] = [UInt8](data)
            let opcode = Opcode.init(code: bytes.first!)
            let jsonData = Data.init(bytes: bytes[1..<bytes.count])
            
            switch opcode {
            case .upvote:
                self?.emitterView.emitImage(UIImage(named: "heart")!)
                break
            case .comment:
                guard let comment = try? JSONDecoder().decode(Comment.self, from: jsonData) else { return }
                self?.comments.append(comment)
                self?.tableView.reloadData()
                break
            case .present:
                let event = GiftEvent(dict: data[0] as! [String: AnyObject])
                self?.giftArea.pushGiftEvent(event)
                break
            default:
                break
            }
        }
        
        textField.addTarget(self, action: #selector(sendComment), for: .editingDidEnd)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.contentInset.top = tableView.bounds.height
        tableView.reloadData()
    }
    
    @IBAction func endTextInput(_ sender: UITapGestureRecognizer) {
        guard sender.state == .ended else {
            return
        }
        textField.resignFirstResponder()
    }
    
    @IBAction func sendComment() {
        let comment = Comment.init(id: nil, title: nil, content: textField.text!, isReply: false, relativeId: room.key!)
        socket.emit(.comment, metadata: comment)
    }
    
    @IBAction func upvote() {
        socket.emit(.upvote, metadata: room)
    }
    
    @IBAction func presentGiftListView() {
        let presentVc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "present") as! GiftChooserViewController
        presentVc.socket = socket
        presentVc.room = room
        
        presentVc.modalPresentationStyle = .custom
        present(presentVc, animated: true, completion: nil)
    }
}

extension LiveOverlayViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return comments.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CommentCell
        cell.comment = comments[(indexPath as NSIndexPath).row]
        return cell
    }
}


class CommentCell: UITableViewCell {
    
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var commentContainer: UIView!
    
    var comment: Comment! {
        didSet {
            titleLabel.text = comment.content
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        commentContainer.layer.cornerRadius = 3
    }
    
    func updateUI() {
//        titleLabel.attributedText = comment.text.attributedComment()
    }
    
}
